package com.aiowang.sml.controller;

import com.aiowang.sml.domain.User;
import com.aiowang.sml.service.UserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author aiowang
 * @description:
 * @date 2021/3/14 23:01
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 新增
     *
     * @param user 对象
     * @return 返回
     */
    @PostMapping(value = "")
    public Boolean add(@RequestBody User user) {

        try {
            user.setId(UUID.randomUUID().toString().replaceAll("-",""));
            userService.save(user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据id删除
     *
     * @param id 实体id
     * @return 成功标识
     */
    @DeleteMapping(value = "/{id}")
    public Boolean delete(@PathVariable("id") String id) {
        try {
            userService.removeById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @DeleteMapping(value = "")
    public Boolean delete(@RequestBody User[] users) {
        try {
            List<String> ids = new ArrayList<>();
            Arrays.stream(users).forEach(s->{
                ids.add(s.getId());
            });
            userService.removeByIds(ids);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 更新
     *
     * @param user 对象
     * @return 成功标识
     */
    @PutMapping(value = "")
    public Boolean edit( @RequestBody User user) {
        try {
            userService.updateById(user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据id查询
     *
     * @param id 实体id
     * @return 成功标识
     */
    @GetMapping(value = "/{id}")
    public User key(@PathVariable("id") String id) {
        try {
            return userService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 分页查询
     *
     * @return ResponseVO-分页实体
     */
    @GetMapping(value = "")
    public IPage<User> page(Integer offset,Integer limit,String name) {
        Page<User> page = new Page<>(offset,limit);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(name!=null, "name", name);
        return userService.page(page,queryWrapper);

    }
}